import re
from hand import Hand
from datetime import datetime

def pokerstars(hh_lines):
    
    hh_pattern = re.compile(r'''
        ^
        PokerStars
        \s
        Game
        \s
        \#            
        (?P<id>\d+):
        .+           
        \(\$(?P<sb>[0-9,.]+)/
        \$(?P<bb>[0-9,.]+)
        .+
        (?P<year>\d{4})
        /(?P<month>\d{2})
        /(?P<day>\d{2})
        \s
        (?P<hour>\d{2})
        :(?P<minute>\d{2})
        :(?P<second>\d{2})
        .+
        Table\s
        '(?P<table_name>.+)'
        \s
        .+
        HOLE\sCARDS
        .+
        Dealt
        .+
        \[(?P<hole_card1>.{2})\s(?P<hole_card2>.{2})\]
        ''', re.MULTILINE | re.VERBOSE | re.DOTALL)
    try:
        hh_dict = hh_pattern.search(hh_lines).groupdict()
    except AttributeError:
        print "ERROR: Check if hand history is corrupt and right parser is being used"
        return None
    
    dealt_cards_pattern = re.compile(r'\*{3}\s.+?\s\*{3}(.*?)\n', re.MULTILINE)
    dealt_cards = max(dealt_cards_pattern.findall(hh_lines), key=len).replace('[', '').replace(']', '').split()
    
    hand = Hand(id=hh_dict['id'],
                table_name=hh_dict['table_name'],
                date_time=datetime(int(hh_dict['year']),
                                   int(hh_dict['month']),
                                   int(hh_dict['day']),
                                   int(hh_dict['hour']),
                                   int(hh_dict['minute']),
                                   int(hh_dict['second'])),
                sb=hh_dict['sb'],
                bb=hh_dict['bb'],
                dealt=dealt_cards,)                  

    player_pattern = re.compile(r'Seat\s(\d):\s([^\s]+?)\s\((\$[0-9,.]+)', re.MULTILINE | re.DOTALL)
    player_list = frozenset(player_pattern.findall(hh_lines))

    for seat_player_stack in player_list:                                    
        hand.addplayer(seat_player_stack)

    action_pattern = re.compile(r'(.+?):\s(posts|calls|folds|checks|raises|bets)\s(.*?)\n', re.MULTILINE)
    for action in action_pattern.findall(hh_lines):
        hand.addaction(action)
    
    return hand